package com.yc.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
//基于Redis的对话记忆存储
public class PersistentChatMemoryStore implements ChatMemoryStore {
    private static final String REDIS_KEY_PREFIX = "chat:memory:"; // Redis键前缀
    private final RedisTemplate<String, String> redisTemplate;

    public PersistentChatMemoryStore(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //生成Redis存储键
    private String getKey(Object memoryId) {
        return REDIS_KEY_PREFIX + memoryId.toString();
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String key = getKey(memoryId);
        String messageJson = redisTemplate.opsForValue().get(key);
        if (messageJson == null || messageJson.isEmpty()) {
            return List.of();  // 无消息时返回空列表
        }
        return ChatMessageDeserializer.messagesFromJson(messageJson);

    }

    @Override
    public void updateMessages(Object memoryId  ,List<ChatMessage> messages) {
        String key = getKey(memoryId);
        String json = ChatMessageSerializer.messagesToJson(messages );
        redisTemplate.opsForValue().set(key,json);
    }

    @Override
    public void deleteMessages(Object o) {

    }
}
